package com.happy_lab_management.demo.student.labBorrowApplication.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.happy_lab_management.context.BaseContext;
import com.happy_lab_management.demo.admin.labSchedule.service.LabScheduleService;
import com.happy_lab_management.demo.admin.semester.service.SemesterService;
import com.happy_lab_management.demo.admin.user.service.StudentService;
import com.happy_lab_management.demo.common.section.service.SectionService;
import com.happy_lab_management.demo.common.weekday.service.WeekdayService;
import com.happy_lab_management.demo.student.labBorrowApplication.service.LabBorrowApplicationService;
import com.happy_lab_management.demo.system.service.SystemService;
import com.happy_lab_management.demo.technician.lab.service.LabService;
import com.happy_lab_management.entity.*;
import com.happy_lab_management.entity.DTO.LabBorrowApplicationDTO;
import com.happy_lab_management.entity.DTO.UserDTO;
import com.happy_lab_management.entity.VO.EquipmentRepairVO;
import com.happy_lab_management.entity.VO.LabBorrowApplicationVO;
import com.happy_lab_management.result.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.lang.System;
import java.sql.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/student/labBorrow")
@RestController("studentLabBorrow")
public class LabBorrowApplicationController {
    @Autowired
    private LabBorrowApplicationService labBorrowApplicationService;
    @Autowired
    private LabService labService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private SemesterService semesterService;
    @Autowired
    private SectionService sectionService;
    @Autowired
    private WeekdayService weekdayService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private LabScheduleService labScheduleService;

    @RequestMapping("/list")
    public Result<IPage<LabBorrowApplicationDTO>> list(@RequestBody LabBorrowApplicationDTO labBorrowApplicationVO,
            @RequestParam( defaultValue = "1") Integer pageNo,
            @RequestParam( defaultValue = "10") Integer pageSize
    ) {
        //获取当前学生的id，并在后续查询获取数据
        Integer userId = BaseContext.getCurrentId();
        Student student = studentService.selectByUserId(userId);
        // 设置查询条件
        QueryWrapper<LabBorrowApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", student.getId());
        //还有其他查询条件，先保留
        if(labBorrowApplicationVO.getWeek()!=null)
            queryWrapper.eq("week",labBorrowApplicationVO.getWeek());

        //查询获取
        Page<LabBorrowApplication> page = new Page<>(pageNo, pageSize);
        //获取分页对象
        IPage<LabBorrowApplication> pageList = labBorrowApplicationService.page(page, queryWrapper);
        //将上面的LabBorrowApplication转换成LabBorrowApplicationDTO
        List<LabBorrowApplicationDTO> dtos = pageList.getRecords().stream().map(er -> {
            //student_id/semester_id/lab_id/weekday/section_id都是要做映射的
            LabBorrowApplicationDTO dto = new LabBorrowApplicationDTO();
            BeanUtils.copyProperties(er,dto);
            //设置学生名字
            dto.setStudentName(student.getName());
            //设置semester_id学期
            Semester semester = semesterService.getById(er.getSemesterId());
            dto.setSemesterName(semester.getSemesterName());
            //实验室编号
            Lab lab = labService.getById(er.getLabId());
            dto.setLabNumber(lab.getLabNumber());
            //实验室类型
            dto.setLabType(Integer.parseInt(lab.getLabType()));
            //节次
            Section section = sectionService.getById(er.getSectionId());
            if(section!=null)
                dto.setSectionName(section.getSectionName());
            //星期几
            Weekday weekday = weekdayService.getById(er.getWeekday());
            dto.setWeekdayName(weekday.getWeekdayName());
            return dto;
        }).toList();
        Page<LabBorrowApplicationDTO> dtoPage = new Page<>();
        dtoPage.setRecords(dtos);
        dtoPage.setTotal(pageList.getTotal());
        dtoPage.setSize(pageList.getSize());
        dtoPage.setCurrent(pageList.getCurrent());
        return Result.success(dtoPage);
    }
    @RequestMapping("/add")
    @Transactional
    public Result<String> add(@RequestBody LabBorrowApplication labBorrowApplication) {
        //检验非空以校验数据
        if(labBorrowApplication.getLabId()==null){
            return Result.error("请选择实验室");
        }
        if(labBorrowApplication.getWeek()==null){
            return Result.error("请选择周次");
        }
        if(labBorrowApplication.getWeekday()==null){
            return Result.error("请选择星期");
        }
        if(labBorrowApplication.getSectionId()==null){
            return Result.error("请选择课程节次");
        }

        //添加现在的用户Id，根据登录用户的userId-》user表格查询id
        Integer userId = BaseContext.getCurrentId();
        Student student = studentService.selectByUserId(userId);
        labBorrowApplication.setStudentId(student.getId());

        //semesterid就应该前端去拿，lab_number也是前端的数据项目，Section也应该通过SectionId
//        semesterid就是当前学期，前台不用传值
        Integer currentSemesterId = systemService.getValueByKey("current_semester_id");
        labBorrowApplication.setSemesterId(currentSemesterId);
        //设置审核状态
        labBorrowApplication.setStatus("未审核"); // 初始状态设置为"未审核"
        //获取当前系统时间作为申请的时间
        labBorrowApplication.setApplicationDate(new java.sql.Date( System.currentTimeMillis()));

        //数据校验
        //查labSchedule
        QueryWrapper<LabSchedule> labScheduleQueryWrapper=new QueryWrapper<>();
        labScheduleQueryWrapper.eq("lab_id",labBorrowApplication.getLabId());
        labScheduleQueryWrapper.eq("semester_id",labBorrowApplication.getSemesterId());
        labScheduleQueryWrapper.between("start_week","end_week",labBorrowApplication.getWeek());
        labScheduleQueryWrapper.eq("weekday",labBorrowApplication.getWeekday());
        labScheduleQueryWrapper.eq("section",labBorrowApplication.getSectionId());

        List<LabSchedule> labScheduleList = labScheduleService.list(labScheduleQueryWrapper);
        if(!labScheduleList.isEmpty()){
            return Result.error("与课表有冲突");
        }

        //查labBorrow

        QueryWrapper<LabBorrowApplication> labBorrowApplicationQueryWrapper =new QueryWrapper<>();
        labBorrowApplicationQueryWrapper.eq("lab_id",labBorrowApplication.getLabId());
        labBorrowApplicationQueryWrapper.eq("semester_id",labBorrowApplication.getSemesterId());
        labBorrowApplicationQueryWrapper.eq("week",labBorrowApplication.getWeek());
        labBorrowApplicationQueryWrapper.eq("weekday",labBorrowApplication.getWeekday());
        labBorrowApplicationQueryWrapper.eq("section_id",labBorrowApplication.getSectionId());

        List<LabBorrowApplication> labBorrowApplications = labBorrowApplicationService.list(labBorrowApplicationQueryWrapper);
        if(!labBorrowApplications.isEmpty()){
            return Result.error("实验室已被借用");
        }
        labBorrowApplicationService.save(labBorrowApplication);
        return Result.success("添加成功");
    }


    // 后端 Java 接口代码
    @RequestMapping("/edit")
    @Transactional
    public Result<String> edit(@RequestBody LabBorrowApplication labBorrowApplication) {
        try {
            //重新赋值需要传递所有的数据才允许修改
            if(labBorrowApplication.getLabId()==null){
                return Result.error("实验室数据丢失");
            }
            if(labBorrowApplication.getWeek()==null){
                return Result.error("周次信息丢失");
            }
            if(labBorrowApplication.getWeekday()==null){
                return Result.error("星期信息丢失");
            }
            if(labBorrowApplication.getSectionId()==null){
                return Result.error("节次信息丢失");
            }
            if(!labBorrowApplication.getStatus().equals("未审核")){
                return Result.error("当前申请已经过审核");
            }
            //审核状态，申请时间，申请人不允许修改
            labBorrowApplication.setStatus(null);
            labBorrowApplication.setApplicationDate(null);
            labBorrowApplication.setStudentId(null);

            // 检查数据库中是否存在该行数据
            LabBorrowApplication labBorrowApplicationOri = labBorrowApplicationService.getById(labBorrowApplication.getId());
            if (labBorrowApplicationOri == null) {
                return Result.error("找不到该数据");
            }
            //设置当前用户
//            Integer userId = BaseContext.getCurrentId();
//            Student student = studentService.selectByUserId(userId);
//            Integer currentStudentId = student.getId();
//            labBorrowApplication.setStudentId(currentStudentId);

            // 将前端传递的除了 ID 字段之外的数据覆盖到原数据
            labBorrowApplication.setStudentId(labBorrowApplication.getStudentId());

            //数据校验
            //查labSchedule
            QueryWrapper<LabSchedule> labScheduleQueryWrapper=new QueryWrapper<>();
            labScheduleQueryWrapper.eq("lab_id",labBorrowApplication.getLabId());
            labScheduleQueryWrapper.eq("semester_id",labBorrowApplication.getSemesterId());
            labScheduleQueryWrapper.between("start_week","end_week",labBorrowApplication.getWeek());
            labScheduleQueryWrapper.eq("weekday",labBorrowApplication.getWeekday());
            labScheduleQueryWrapper.eq("section",labBorrowApplication.getSectionId());

            List<LabSchedule> labScheduleList = labScheduleService.list(labScheduleQueryWrapper);
            if(!labScheduleList.isEmpty()){
                return Result.error("与课表有冲突");
            }

            //查labBorrow
            QueryWrapper<LabBorrowApplication> labBorrowApplicationQueryWrapper =new QueryWrapper<>();
            labBorrowApplicationQueryWrapper.ne("id",labBorrowApplication.getId());
            labBorrowApplicationQueryWrapper.eq("lab_id",labBorrowApplication.getLabId());
            labBorrowApplicationQueryWrapper.eq("semester_id",labBorrowApplication.getSemesterId());
            labBorrowApplicationQueryWrapper.eq("week",labBorrowApplication.getWeek());
            labBorrowApplicationQueryWrapper.eq("weekday",labBorrowApplication.getWeekday());
            labBorrowApplicationQueryWrapper.eq("section_id",labBorrowApplication.getSectionId());
            List<LabBorrowApplication> labBorrowApplications = labBorrowApplicationService.list(labBorrowApplicationQueryWrapper);
            if(!labBorrowApplications.isEmpty()){
                return Result.error("实验室已被借用");
            }

            // 更新申请数据
            labBorrowApplicationService.updateById(labBorrowApplication);

            return Result.success("修改成功");
        } catch (Exception e) {
            return Result.error("修改失败: " + e.getMessage());
        }
    }


    @RequestMapping("/finished")
    public Result<String> setStatus(@RequestParam Integer id) {
        try {
            if(id==null){
                Result.error("请输入id");
            }
            LabBorrowApplication labBorrowApplication = labBorrowApplicationService.getById(id);
            if (labBorrowApplication == null) {
                return Result.error("找不到对应的申请记录");
            }

            // 更新状态为“使用完毕”
            labBorrowApplication.setStatus("使用完毕");
            labBorrowApplicationService.updateById(labBorrowApplication);
            return Result.success("成功修改状态为：使用完毕");
        } catch (Exception e) {
            // 捕获可能出现的异常
            return Result.error("修改状态失败: ");
        }
    }

    @RequestMapping("/delete")
    public Result<String> delete(@RequestBody Map<String, Integer> requestBody) {
        Integer id = requestBody.get("id");
        try {
            boolean success = labBorrowApplicationService.removeById(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败: " + e.getMessage());
        }
    }
    /**
     * 废弃的接口，太难用了
     */
//    @RequestMapping("add")
//    public Result<String> add(@RequestBody LabBorrowApplicationDTO labBorrowApplicationDTO) {
//        LabBorrowApplication labBorrowApplication = new LabBorrowApplication();
//        //获取仙现在的用户Id
//        Integer userId = BaseContext.getCurrentId();
//        Student student = studentService.selectByUserId(userId);
//
//        labBorrowApplication.setStudentId(student.getId());
//
//        QueryWrapper<Semester> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("semester_name", labBorrowApplicationDTO.getSemesterName());
//        Semester semester = semesterService.getOne(queryWrapper);
//        labBorrowApplication.setSemesterId(semester.getId());
//
//        QueryWrapper<Lab> queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("lab_number", labBorrowApplicationDTO.getLabNumber());
//        Lab lab = labService.getOne(queryWrapper1);
//        labBorrowApplication.setLabId(lab.getId());
//
//        QueryWrapper<Section> queryWrapper2 = new QueryWrapper<>();
//        queryWrapper2.eq("section_name", labBorrowApplicationDTO.getSectionName());
//        Section section = sectionService.getOne(queryWrapper2);
//        labBorrowApplication.setSectionId(section.getId());
//
//        labBorrowApplication.setWeek(labBorrowApplicationDTO.getWeek());
//        labBorrowApplication.setReason(labBorrowApplicationDTO.getReason());
//        labBorrowApplication.setStatus("未审核"); // 初始状态设置为"未审核"
//        labBorrowApplication.setSemesterId(labBorrowApplication.getSemesterId());// 从前端获取 semesterId 值
//        labBorrowApplicationService.save(labBorrowApplication);
//
//        return Result.success("添加成功");
//    }


}
